﻿CREATE PROCEDURE [dbo].[Referal_SetSharedKey]
	@userId UNIQUEIDENTIFIER = NULL,
	@sharedHashTag NVARCHAR(MAX)
AS
BEGIN
	DECLARE @chapterId BIGINT
	DECLARE @textId BIGINT
	DECLARE @refUserId UNIQUEIDENTIFIER

	SELECT @chapterId = [TextId], @textId = [TextId], @refUserId = [UserId]
	FROM [dbo].[user_Share] 
	WHERE [HashCode] = @sharedHashTag

	SELECT @chapterId 'ChapterId', @textId 'TextIdHash', @refUserId 'RefUserId'

	IF @chapterId IS NULL OR @userId IS NULL OR @userId = @refUserId
		RETURN

	IF EXISTS (SELECT * FROM [user_Referals] WHERE [UserId] = @userId AND [TextId] = @chapterId)
	BEGIN
		UPDATE [dbo].[user_Referals]
		SET [ReferalUserId] = @refUserId
		WHERE [UserId] = @userId AND [TextId] = @chapterId
	END
	ELSE
	BEGIN
		INSERT INTO [dbo].[user_Referals] ([UserId], [ReferalUserId], [TextId])
		VALUES (@userId, @refUserId, @chapterId)
	END

END